package com.hk.player.module;

import android.view.View;

import com.zhoug.common.utils.LogUtils;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @author: zhoug
 * @since: 2025-08-08
 */
public class AutoPlayController {
    private static final boolean DEBUG = false;
    private static final String TAG = ">>>AutoPlayController";
    private final RecyclerView mRecyclerView;
    private final LinearLayoutManager mLayoutManager;
    private SwitchPlayListener mSwitchPlayListener;

    public AutoPlayController(@NonNull RecyclerView recyclerView, @NonNull LinearLayoutManager layoutManager) {
        this.mRecyclerView = recyclerView;
        this.mLayoutManager = layoutManager;
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private int mState = -1;
            private int mScrollY = 0;
            private boolean shouldPause = false;

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                mState = newState;
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
                        if (DEBUG) {
                            LogUtils.d(TAG, "滚动停止");
                        }
                        mScrollY = 0;
                        checkPlayableItem();
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        if (DEBUG) {
                            LogUtils.d(TAG, "拖动");
                        }
                        shouldPause = true;
                        //需要暂停当前播放的视频
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        if (DEBUG) {
                            LogUtils.d(TAG, "惯性滚动");
                        }
                        break;
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                mScrollY += dy;
                if (DEBUG) {
                    LogUtils.d(TAG, "mScrollY:" + mScrollY);
                }
                if (shouldPause
                        && (mState == RecyclerView.SCROLL_STATE_DRAGGING || mState == RecyclerView.SCROLL_STATE_SETTLING)
                        && Math.abs(mScrollY) > 10) {
                    shouldPause = false;
                    if (DEBUG) {
                        LogUtils.d(TAG, "开始滚动了");
                    }
                    if (mSwitchPlayListener != null) {
                        mSwitchPlayListener.onStartScroll();
                    }
                }
            }
        });
    }


    public void setSwitchPlayListener(SwitchPlayListener switchPlayListener) {
        this.mSwitchPlayListener = switchPlayListener;
    }


    private void checkPlayableItem() {
        int centerPosition = findCenterVisiblePosition();
        if (mSwitchPlayListener != null) {
            RecyclerView.ViewHolder viewHolder = mRecyclerView.findViewHolderForAdapterPosition(centerPosition);
            if(viewHolder!=null){
                mSwitchPlayListener.onCenterItemChange(viewHolder);
            }
        }
    }

    /**
     * 查找距离列表中心最近的Item
     *
     * @return
     */
    private int findCenterVisiblePosition() {
        int firstVisibleItemPosition = mLayoutManager.findFirstVisibleItemPosition();
        int lastVisibleItemPosition = mLayoutManager.findLastVisibleItemPosition();
        // 计算屏幕中心Y坐标
        float screenCenterY = mRecyclerView.getHeight() / 2f;
        int candidatePos = -1;
        float minDistance = Float.MAX_VALUE; // 记录与中心的最小距离
        for (int i = firstVisibleItemPosition; i < lastVisibleItemPosition; i++) {
            View view = mLayoutManager.findViewByPosition(i);
            if (view == null) continue;
            float viewCenterY = (view.getTop() + view.getBottom()) / 2f;
            // 计算与屏幕中心的距离（绝对值）
            float distanceToCenter = Math.abs(viewCenterY - screenCenterY);
            // 选择距离中心最近的Item
            if (distanceToCenter < minDistance) {
                minDistance = distanceToCenter;
                candidatePos = i;
            }
        }
        return candidatePos;
    }

    public interface SwitchPlayListener {
        void onStartScroll();

        void onCenterItemChange(RecyclerView.ViewHolder viewHolder);
    }
}
